package admin.models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.List;

import javax.cache.Cache;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import entities.SubmitSite;

public class SubmitSiteModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "submit_site_";
	
	private static SubmitSiteModel instance = null;

	public static SubmitSiteModel getInstance() {
		if (instance == null) {
			instance = new SubmitSiteModel();
		}
		
		return instance;
	}
	
	private SubmitSiteModel() {
		try {
			ObjectifyService.register(SubmitSite.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<SubmitSite> list(int page, int limit) {
		List<SubmitSite> sites = new ArrayList<SubmitSite>();
		
		int start = (page - 1) * limit;
		sites = ofy.query(SubmitSite.class).limit(limit).offset(start).list();
		
		return sites;
	}
	
	public List<SubmitSite> getAll() {
		List<SubmitSite> sites = new ArrayList<SubmitSite>();
		
		try {
			sites = ofy.query(SubmitSite.class).list();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		return sites;
	}
	
	public List<SubmitSite> getSiteActive() {
		List<SubmitSite> sites = new ArrayList<SubmitSite>();
		
		try {
			sites = ofy.query(SubmitSite.class).filter("status", 1).list();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return sites;
	}
	
	public void insert(SubmitSite site) {
		try {
			String cacheName = prefix + "_all_site";
			cache.remove(cacheName);
		} catch (Exception e) {}
		
		ofy.put(site);
	}
	
	public void delete(SubmitSite site) {
		try {
			String cacheName = prefix + "_all_site";
			cache.remove(cacheName);
		} catch (Exception e) {}
		
		ofy.delete(site);
		
	}
	
	public SubmitSite get(String id) {
		SubmitSite site = new SubmitSite();
		try {
			site = ofy.get(new Key<SubmitSite>(SubmitSite.class, id));
		} catch (Exception e) {
			site = null;
		}
		
		return site;
	}
}
